package com.android.settings.ios;

import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;

import androidx.preference.Preference;
import androidx.preference.SwitchPreference;

import com.android.settings.ios.view.OsPreference;
import com.android.settings.ios.view.OsPreferenceCategory;
import com.android.settings.ios.view.OsSwitchPreference;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

public class SettingsFragment extends BaseFragment {

    private final int MSG_ADD_OTHER_APPS = 1;

    private OsPreferenceCategory mOtherAppsListCategory;
    private final List<AppData> mOtherAllApps = new ArrayList<>();

    private OsSwitchPreference mAirplanePref;
    private Preference mWifiPref;

    @Override
    public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
        addPreferencesFromResource(R.xml.os_setting_main_fragment);
        mOtherAppsListCategory = findPreference("other_apps_list");

        mAirplanePref = findPreference("menu_airplane_mode");
        mWifiPref = findPreference("menu_wifi");

        new Thread(new Runnable() {

            @Override
            public void run() {
                loadApps();
            }
        }).start();
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    protected void updateTitleIfNeeded() {

    }

    @Override
    protected void onActionBarScrollChanged(float alpha) {
        if (mMainActivity instanceof SettingsMainActivity) {
            ((SettingsMainActivity) mMainActivity).updateMainBarBackgroundAlpha(alpha);
        }
    }

    @Override
    public boolean onPreferenceTreeClick(Preference preference) {
        final String key = preference.getKey();
        if ("menu_airplane_mode".equals(key)) {

        }
        if (preference.getIntent() == null) {
            OsUtils.notifyMenuSelected(preference);
        }
        return super.onPreferenceTreeClick(preference);
    }

    private final Handler mHandler = new Handler(Looper.myLooper()) {

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_ADD_OTHER_APPS:
                    for (AppData app : mOtherAllApps) {
                        mOtherAppsListCategory.addPreference(createOsPreference(app));
                    }
                    mOtherAppsListCategory.updateItemBackground();
                    break;
            }
        }
    };

    private final static class AppData {
        String pkgName;
        String title;
        Bitmap bitmap;
        Bundle bundle;
    }

    private OsPreference createOsPreference(AppData app) {
        OsPreference preference = new OsPreference(getActivity(), true);
        preference.setTitle(app.title);
        preference.setIconBitmap(app.bitmap);
        preference.setShowRightArrow(false);
        preference.setKey(app.pkgName);
        preference.setAppArgs(app.bundle);
        return preference;
    }

    private void loadApps() {
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_LAUNCHER);
        PackageManager pm = getContext().getPackageManager();
        List<ResolveInfo> allResolves = pm.queryIntentActivities(intent, 0);
        mOtherAllApps.clear();
        OsUtils.sTotalAppCount = allResolves.size();
        Bitmap bound = BitmapFactory.decodeResource(getResources(), R.drawable.ip_ic_menu_wifi);
        for (int i = 0; i < allResolves.size(); i++) {
            ResolveInfo info = allResolves.get(i);
            int flags = info.activityInfo.applicationInfo.flags;
            if ((flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
                continue;
            }
            if ((flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0) {
                continue;
            }
            String srcDir = info.activityInfo.applicationInfo.sourceDir;
            if (srcDir == null || !srcDir.startsWith("/data")) {
                continue;
            }
            AppData appData = new AppData();
            Drawable drawable = info.loadIcon(pm);
            if (drawable instanceof BitmapDrawable) {
                appData.bitmap = Bitmap.createScaledBitmap(((BitmapDrawable) drawable).getBitmap(), bound.getWidth(), bound.getHeight(), true);
                appData.title = info.loadLabel(pm).toString();
                appData.pkgName = info.activityInfo.packageName;
                appData.bundle = new Bundle();
                appData.bundle.putString("packageName", appData.pkgName);
                mOtherAllApps.add(appData);
            }
        }

        if (!mOtherAllApps.isEmpty()) {
            mOtherAllApps.sort(new Comparator<AppData>() {

                @Override
                public int compare(AppData o1, AppData o2) {
                    return o1.title.compareTo(o2.title);
                }
            });
            mHandler.sendEmptyMessage(MSG_ADD_OTHER_APPS);
        }
    }
}
